const Mock = require('mockjs')
const Random = Mock.Random
/**
 * @param {string} url
 * @returns {Object}
 */
function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach((v) => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * 生成随机字符组成的对象数组
 * @param {[createObj]}
 * @returns {Array}
 */
function createArr(objs, l) {
  const arrL = l ? l : Random.integer(4, 100)
  const results = []
  for (let index = 0; index <= arrL; index++) {
    const obj = {}
    for (let i = 0; i < objs.length; i++) {
      obj[objs[i].k] = createObj(objs[i].v)
    }
    results.push(obj)
  }
  return results
}

/**
 * 生成随机字符组成的对象数组
 * @param { {key:name value:{length: 'length', type: ''， range: ''}} }
 * name 字段名，length: 长度， type: Mock支持的数据类型 range: 长度区间
 * @returns {String/int/bool}
 */
function createObj(v) {
  if (v.t) {
    switch (v.t) {
      case 'Boolean':
        return Random.boolean
      case 'name':
        // 默认中文名
        return Random.cname()
      case 'string':
        return Random.string(v.l ? v.l : 10)
      case 'int':
        return Random.integer(v.r ? v.r[0] : 0, v.r ? v.r[1] : 1000)
      case 'date':
        return Random.now('second')
      case 'custom': {
        const i = Random.integer(0, v.c.length - 1)
        return v.c[i]
      }
      default:
        break
    }
  }
}

module.exports = {
  param2Obj,
  createArr,
}
